﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Snowflake.Core;
using Yitter.IdGenerator;

namespace NetMicro.Core.Snowflake
{
    /// <summary>
    /// 雪花算法注入
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 配置分布式雪花算法
        /// </summary>
        public static IServiceCollection AddDistributedSnowflake<T>(this IServiceCollection services, IConfiguration configuration)
            where T : class, IDistributedSnowflakeId
        {
            services.AddSingleton<IDistributedSnowflakeId, T>();
            services.AddSnowflake(configuration);
            return services;
        }


        /// <summary>
        /// 配置雪花算法，机器码需要保证每台服务器该值不一样
        /// </summary>
        public static IServiceCollection AddSnowflake(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<SnowflakeOptions>(configuration.GetSection("Snowflake"))
                .AddSingleton(porvider =>
            {
                //雪花算法初始化配置项
                var options = porvider.GetService<IOptions<SnowflakeOptions>>();
                int workerId = options?.Value?.WorkerId ?? 6;
                int datacenterId = options?.Value?.DatacenterId ?? 0;
                return new IdWorker(workerId, datacenterId);
            });
            //添加雪花漂移算法
            var options = new IdGeneratorOptions() { WorkerId = 1 };
            YitIdHelper.SetIdGenerator(options);

            return services;
        }

    }
}
